<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;

use App\Http\Controllers\Controller;
use App\Models\AdminUser as User;
use App\Models\WechatRecover;
use App\Models\RoleUser;
use App\Models\Wechat;

class WechatRecoverController extends Controller
{
    protected $fields = [
        
    ];

    public function __construct(Request $request)
    {
      /*   $this->uid = auth()->user()->id;
        $condition = [['wechats.uid', '>', 0],];
        if($this->uid > 1){
            $condition = array('wechats.uid'=>$this->uid);
			
        }
        $this->condition = $condition; */
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
		//查询所有下属id
		$ids = User::where('pid',auth()->user()->id)->lists('id')->toArray();
		$kids = User::whereIn('pid',$ids)->lists('id')->toArray();
		$wids = array_values($ids)+array_values($kids);
        if ($request->ajax()) {
            $data = array();
            $data['draw'] = $request->get('draw');
            $start = $request->get('start');
            $length = $request->get('length');
            $order = $request->get('order');
            $columns = $request->get('columns');
            $search = $request->get('search');
            $data['recordsTotal'] = WechatRecover::
					 where(function ($query) use ($wids){
						if(getRoleName(auth()->user()->id)=='超级管理员'||auth()->user()->id==1){
								
							}else{
								$query->whereIn('wechat_recovers.aid',$wids);
							}
					})->count();
            if (strlen($search['value']) > 0) {
                $data['recordsFiltered'] = WechatRecover::leftJoin("wechat_groups", "wechat_groups.id", "=", "wechats.group")->where(function ($query) use ($search) {
                    $query->where('wx_num', 'LIKE', '%' . $search['value'] . '%')
                        ->orWhere('wx_nike', 'like', '%' . $search['value'] . '%')
						->orWhere('wechat_groups.name', 'like', '%' . $search['value'] . '%');
                })->where(function ($query) use ($wids){
						if(getRoleName(auth()->user()->id)=='超级管理员'||auth()->user()->id==1){
								
							}else{
								$query->whereIn('wechat_recovers.aid',$wids);
							}
					})->count();

                $data['data'] = WechatRecover::select("wechats.*", "wechat_groups.name","admin_users.name as username")
                    ->leftJoin("wechat_groups", "wechat_groups.id", "=", "wechats.group")
					->leftJoin("admin_users", "wechat_groups.tid", "=", "admin_users.id")
                    ->where(function ($query) use ($search) {
                        $query->where('wx_num', 'LIKE', '%' . $search['value'] . '%')
                            ->orWhere('wx_nike', 'like', '%' . $search['value'] . '%')
							->orWhere('wechat_groups.name', 'like', '%' . $search['value'] . '%');
                    })
					->where(function ($query) use ($wids){
						if(getRoleName(auth()->user()->id)=='超级管理员'||auth()->user()->id==1){
								
							}else{
								$query->whereIn('wechat_recovers.aid',$wids);
							}
					})
                    ->skip($start)->take($length)
                    ->orderBy($columns[$order[0]['column']]['data'], $order[0]['dir'])
                    ->get();
            } else {
                /* $data['recordsFiltered'] = Wechat::where(session('authAdminCondition'))->count(); */
				$data['recordsFiltered'] = $data['recordsTotal'];
                $data['data'] = WechatRecover::select("wechat_recovers.*", "wechats.wx_num","admin_users.name as username","h.name as hname")
                    ->leftJoin("wechats", "wechats.id", "=", "wechat_recovers.wid")
					->leftJoin("admin_users", "wechat_recovers.aid", "=", "admin_users.id")
					->leftJoin("admin_users as h", "wechat_recovers.hid", "=", "admin_users.id")
					->where(function ($query) use ($wids){
						if(getRoleName(auth()->user()->id)=='超级管理员'||auth()->user()->id==1){
								
							}else{
								$query->whereIn('wechat_recovers.aid',$wids);
							}
					})
                    ->skip($start)->take($length)
                    ->orderBy($columns[$order[0]['column']]['data'], $order[0]['dir'])
                    ->get();
            }
            return response()->json($data);
        }
		$data['role'] = RoleUser::where('user_id',auth()->user()->id)->first();
        return view('admin.wechatrecover.index',$data);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $data = [];
        foreach ($this->fields as $field => $default) {
            $data[$field] = old($field, $default);
        }
        $userList = User::lists('name', 'id');
        $data['userList'] = $userList;
        $uid = auth()->user()->id;
       /*  
	   $data['wechatgroup'] = WechatGroup::select('wechat_groups.id', 'wechat_groups.name', 'admin_users.name as username')
            ->leftJoin('admin_users', 'admin_users.id', '=', 'wechat_groups.uid')
            ->where(function ($query) use ($uid) {
                if ($uid != 1) {
                    $query->where('uid', '=', auth()->user()->id)->orWhere('uid', '=', 1);
                }
            })->get(); 
		*/
		$wechatgroup1 = WechatGroup::select("wechat_groups.id","wechat_groups.name")
			->join('wechat_group_users','wechat_group_users.gid','=','wechat_groups.id')
			->where(function($query)use($uid){
				$query->where('wechat_group_users.uid',$uid);
			})->get()->toArray();
		$wechatgroup2 = WechatGroup::select("wechat_groups.id","wechat_groups.name")->where('wechat_groups.uid',$uid)->get()->toArray();
		$data['wechatgroup'] = array_merge($wechatgroup1,$wechatgroup2);
        return view('admin.wechat.create', $data);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        if(empty($request->wx_num))  return redirect()->back()->withErrors("微信号不能为空！");
        if(empty($request->wx_nike))  return redirect()->back()->withErrors("微信昵称不能为空！");
		$wx_nums = $request->get('wx_num');
		$wx_numArr = explode("\n",$wx_nums); 
		foreach (array_keys($this->fields) as $field) {
			if ($field == 'uid') {
				if (auth()->user()->id != 1) {
					$wxArr[$field]=getTid(auth()->user()->id);
					continue;
				}
			}
			if ($field == 'username') {
				if (auth()->user()->id != 1) {
					$wxArr[$field]=auth()->user()->name;
					continue;
				}
			}
			if($field=='wx_num'){
				continue;
			}
			if($field=='tid'){
				$wxArr[$field] = getTid(auth()->user()->id);
				continue;
			}
			$wxArr[$field] = $request->get($field);
		}
		$wxArrs = [];$qc = [];
		foreach($wx_numArr as $wx){
			$wx_num = trim($wx);
			if(in_array($wx_num,$qc)){ //如果重复数组,跳过
				continue;
			}else{
				$qc[]=$wx_num;
			}
			if(!$this->validWechat($wx_num,$request->wx_nike)){
				$wxArr['wx_num']=$wx_num;
				$wxArrs[]=$wxArr;
			}
		}
		$wechat = new Wechat();
		$wechat->insert($wxArrs);
        return redirect('/admin/wechat')->withSuccess('添加成功！');
    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $wechat = Wechat::find((int)$id);
        if (!$wechat) return redirect('/admin/wechat')->withErrors("找不到该微信号!");
        foreach (array_keys($this->fields) as $field) {
            $data[$field] = old($field, $wechat->$field);
        }
        $data['id'] = (int)$id;
        $userList = User::lists('name', 'id');
        $data['userList'] = $userList;
        $uid = auth()->user()->id;
       /*  $data['wechatgroup'] = WechatGroup::select('wechat_groups.id', 'wechat_groups.name', 'admin_users.name as username')->leftJoin('admin_users', 'admin_users.id', '=', 'wechat_groups.uid')->where(function ($query) use ($uid) {
            if ($uid != 1) {
                $query->where('uid', '=', auth()->user()->id)->orWhere('uid', '=', 1);
            }
        })->get(); */
		$wechatgroup1 = WechatGroup::select("wechat_groups.id","wechat_groups.name")->join('wechat_group_users','wechat_group_users.gid','=','wechat_groups.id')->where(function($query)use($uid){
			$query->where('wechat_group_users.uid',$uid);
		})->get()->toArray();
		$wechatgroup2 = WechatGroup::select("wechat_groups.id","wechat_groups.name")->where('wechat_groups.uid',$uid)->get()->toArray();
		$data['wechatgroup'] = array_merge($wechatgroup1,$wechatgroup2);
        return view('admin.wechat.edit', $data);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
		
        $this->validate($request, ['wx_num' => 'required|unique:wechats,id,' . $id]);
        $wechat = Wechat::find((int)$id);
		$status = $wechat->status;//原状态，判断是否需要更新模板
        foreach (array_keys($this->fields) as $field) {
			if ($field == 'uid') {
				//if (auth()->user()->id != 1) {
					//if($wechat->group)
					//$wechat->$field=auth()->user()->id;
					continue;
				//}
			}
			if($field=='tid'){
				//$wechat->$field = getTid(auth()->user()->id);
				continue;
			}
            $wechat->$field = $request->get($field);
        }
        $wechat->save();
		//查询添加了该微信的分组
		if($status!=$request->get('status')){
			$groups = Group::where('wechat_list','LIKE','%'.$wechat->wx_num.'%')->get();
			foreach($groups as $group){
				$wechat_list = explode(',',$group->wechat_list);
				if(in_array($request->get('wx_num'),$wechat_list)){
					//调用更新模板函数
					$r = new Request();
					$r->id = $group->id;
					$domain = new DomainController();
					$domain->crossGUpTpl($r);
				}
			}
		}
		
        return redirect('/admin/wechat')->withSuccess('更新成功！');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id or string ids=>1,2,3,4,5,6
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        if (is_numeric($id)) {
            $tag = Wechat::find((int)$id);
            if ($tag) {
				$tag->status = 0;
				$tag->save();
				//查询添加了该微信的分组
				//if($status!=$request->get('status')){
					$groups = Group::where('wechat_list','LIKE','%'.$tag->wx_num.'%')->get();
					foreach($groups as $group){
						$wechat_list = explode(',',$group->wechat_list);
						if(in_array($tag->wx_num,$wechat_list)){
							//调用更新模板函数
							$r = new Request();
							$r->id = $group->id;
							$domain = new DomainController();
							$domain->crossGUpTpl($r);
						}
					}
				//}
                $tag->delete();
            } else {
                return redirect()->back()
                    ->withErrors("删除失败");
            }
        } else {
            $idArr = explode(',', $id);
			$recordRows = Wechat::whereIn('id', $idArr)->get();
			foreach($recordRows as $rr){
				$rr->status = 0;
				$rr->save();
			//查询添加了该微信的分组
				$groups = Group::where('wechat_list','LIKE','%'.$rr->wx_num.'%')->get();
				foreach($groups as $group){
					$wechat_list = explode(',',$group->wechat_list);
					if(in_array($rr->wx_num,$wechat_list)){
						//调用更新模板函数
						$r = new Request();
						$r->id = $group->id;
						$domain = new DomainController();
						$domain->crossGUpTpl($r);
					}
				}
			}
			
			
            $recordRow = Wechat::whereIn('id', $idArr)->delete();
            if (!$recordRow) {
                return redirect()->back()
                    ->withErrors("删除失败");
            }
        }
        return redirect()->back()
            ->withSuccess("删除成功");
    }
	//申请回收
	public function recover(Request $request,$id){
		if($request->type=='recover'){
			 if (is_numeric($id)) {
				$tag = WechatRecover::find((int)$id);
				if ($tag) {
					$wechat = Wechat::find($tag->wid);
					$wechat->recover = 0;
					$wechat->group = 0;
					$wechat->save();
					$tag->status = 1;
					$tag->hid = auth()->user()->id;
					$tag->save();
					event(new \App\Events\userActionEvent('\App\Models\WechatRecover',$tag->wid, 3, '同意回收申请['.$wechat->wx_num.']'));
				} else {
					return redirect()->back()
						->withErrors("同意失败");
				}
			} else {
				$idArr = explode(',', $id);
				$recordRow = WechatRecover::whereIn('id', $idArr)->get();
				$wx_nums='';$wid_arr=[];
				foreach($recordRow as $rr){
					$wechat = Wechat::find($rr->wid);
					$wx_nums.=$wechat->wx_num.'、';
					$wid_arr[] = $rr->wid;
					//$wechat->recover = 0;
					//$wechat->group = 0;
					//$wechat->save();
					//$rr->status = 1;
					//$rr->hid = auth()->user()->id;
					//$rr->save();
				}
				Wechat::whereIn('id',$wid_arr)->update(['recover'=>0,'group'=>0]);
				WechatRecover::whereIn('id', $idArr)->update(['status'=>1,'hid'=>auth()->user()->id]);
				event(new \App\Events\userActionEvent('\App\Models\WechatRecover',0, 3, '同意回收申请['.$wx_nums.']'));
				if (!$recordRow) {
					return redirect()->back()
						->withErrors("同意失败");
				}
			}
			return redirect()->back()->withSuccess("同意成功");
		}elseif($request->type=='stop'){
			if (is_numeric($id)) {
				$tag = WechatRecover::find((int)$id);
				if ($tag) {
					$wechat = Wechat::find($tag->wid);
					$wechat->recover = 0;
					$wechat->save();
					$tag->status = 2;
					$tag->hid = auth()->user()->id;
					$tag->save();
					event(new \App\Events\userActionEvent('\App\Models\WechatRecover',$tag->wid, 3, '拒绝回收申请['.$wechat->wx_num.']'));
				} else {
					return redirect()->back()
						->withErrors("拒绝失败");
				}
			} else {
				$idArr = explode(',', $id);
				$recordRow = WechatRecover::whereIn('id', $idArr)->get();
				$wx_nums='';$wid_arr=[];
				foreach($recordRow as $rr){
					$wechat = Wechat::find($rr->wid);
					$wx_nums.=$wechat->wx_num.'、';
					$wid_arr[] = $rr->wid;
					//$wechat->recover = 0;
					//$wechat->save();
					//$rr->status = 2;
					//$rr->hid = auth()->user()->id;
					//$rr->save();
				}
				Wechat::whereIn('id',$wid_arr)->update(['recover'=>0]);
				WechatRecover::whereIn('id', $idArr)->update(['status'=>2,'hid'=>auth()->user()->id]);
				event(new \App\Events\userActionEvent('\App\Models\WechatRecover',0, 3, '拒绝回收申请['.$wx_nums.']'));
				if (!$recordRow) {
					return redirect()->back()
						->withErrors("拒绝失败");
				}
			}
			return redirect()->back()
						->withSuccess("拒绝成功");
		}
		
	}
}